//
//  TFPhotoPickerViewController.m
//  PhotoDemoProject
//
//  Created by TFAppleWork-Summer on 2016/11/11.
//  Copyright © 2016年 TFAppleWork-Summer. All rights reserved.
//

#import "TFPhotoPickerViewController.h"
//工具类
#import "TFPhotoPickerHelper.h"
#import "TFPhotoPickerCollectionViewFlowLayout.h"
#import "TFPhotoHandler.h"
#import "TFSinglePhotoPickerHelper.h"
#import "TFPhotoResourceHelper.h"
#import "UIColor+TFPhoto.h"
//UI视图
#import "TFPhotoPickerAlbumButton.h"
#import "TFPhotoPickerAlbumView.h"
#import "TFPhotoPickerLoadingView.h"
#import "TFPhotoAuthDeniedView.h"
#import "TFPhotoPickerCollectionViewSectionHeaderView.h"
#import "TFPhotoPickerItemCollectionViewCell.h"
#import "TFPhotoPickerPhotoBrowserDisplayCell.h"
#import "TFPhotoPickerPhotoBrowserVideoDisplayCell.h"
#import "TFPhotoPickerTakePhotoCell.h"

typedef NS_ENUM(NSUInteger, TFPhotoPickerShowType) {
    TFPhotoPickerShowTypeMoment,
    TFPhotoPickerShowTypeAlbum,
};

static const NSInteger kTFPhotoPickerNoPhotosViewTag = 111;
static const NSInteger kTFPhotoPickerAlbumViewTag = 122;
static const NSInteger kTFPhotoPickerSectionHeaderViewTag = 1111;

@interface TFPhotoPickerViewController ()<PHPhotoLibraryChangeObserver,TFSinglePhotoPickerHelperDelegate,TFPhotoPickerAlbumViewDelegate>

@property (nonatomic, strong) UIButton *albumListButton;

@property (nonatomic, strong, readwrite) UICollectionView *collectionView;

@property (nonatomic, strong, readwrite) UIView *bottomView;

@property (nonatomic, strong) NSMutableArray<TFPhotoPickerMomentModel *> *momentArray;//时刻模型数组

@property (nonatomic, strong) NSMutableArray *albumListArr;//相册列表数组

@property (nonatomic, strong) NSMutableArray *allItemsArr;//所有图片模型数组

@property (nonatomic, strong) NSMutableArray *showModelsArr;///<显示的模型数组

@property (nonatomic, assign) TFPhotoPickerShowType showType;///<当前显示数据类型

@property (nonatomic, assign) PHAssetCollectionSubtype currentCollectionSubtype;///<选择的相册类型

@property (nonatomic, strong) UIBarButtonItem *selectCountItem;///<当前选中数量item

@property (nonatomic, strong) NSIndexPath *previousSelectedIndexPath;///<上一个选中的item索引

@property (nonatomic, strong) PHFetchResult<PHAssetCollection *> *momentFetchResult;///<时刻检索到的结果集

@property (nonatomic, strong) NSIndexPath *selectIndexPath;///<跳转图片浏览器时选中的item

@property (nonatomic, strong) NSString *autoSelectAssetIdentifier;///<自定选择的本地唯一标志位

@property (nonatomic, assign) TFPhotoPickerStyle photoPickerStyle;///<图片选择器样式

@end

@implementation TFPhotoPickerViewController

- (instancetype)initWithStyle:(TFPhotoPickerStyle)photoPickerStyle {
    self = [super init];
    if (self) {
        self.photoPickerStyle = photoPickerStyle;
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.photoPickerStyle = TFPhotoPickerStyleMomentGroup;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor tfPhoto_hexColorWith:@"#f2f2f2"];
    [self.view addSubview:self.collectionView];
    if (self.selectMaxCount>1) {
        //添加底部工具栏
        if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerCustomBottomView:)]) {
            self.bottomView = [self.delegate photoPickerViewControllerCustomBottomView:self];
        }
        else {
            self.bottomView = [self getDefaultBottomView];
            if ([self.delegate respondsToSelector:@selector(photoPickerViewController:didCreatedBottomBar:)]) {
                [self.delegate photoPickerViewController:self didCreatedBottomBar:(UIToolbar *)self.bottomView];
            }
        }
        self.bottomView.hidden = YES;
        [self.view addSubview:self.bottomView];
        [self.collectionView setContentInset:UIEdgeInsetsMake(0, 0, CGRectGetHeight(self.bottomView.frame)?:49.0, 0)];
    }
    //给子view添加约束
    if ([self.delegate respondsToSelector:@selector(photoPickerViewController:customConstraintsWithSubView:bottomView:)]) {
        [self.delegate photoPickerViewController:self customConstraintsWithSubView:self.collectionView bottomView:self.bottomView];
    }
    else {
        [self addConstraintsForSubViews];
    }
    
    if (self.presentingViewController) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"取消"] style:UIBarButtonItemStylePlain target:self action:@selector(p_navigationItemCancelLeftItemAction)];
    }

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"确定"] style:UIBarButtonItemStylePlain target:self action:@selector(p_navigationItemConfirmRightItemAction)];
    
    //图片预览
    self.navigationItem.titleView = self.albumListButton;
    
    //添加约束
    [self p_checkAuthorizationStatus];
    
    //检测photo变化
    [[PHPhotoLibrary sharedPhotoLibrary]registerChangeObserver:self];
}

#pragma mark - public 

- (void)addConstraintsForSubViews {
    if (self.selectMaxCount>1) {
        self.bottomView.translatesAutoresizingMaskIntoConstraints = NO;
        self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
        NSDictionary *viewDic = @{@"collectionView":self.collectionView,@"bottomView":self.bottomView};
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[collectionView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bottomView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[collectionView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[bottomView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint constraintWithItem:self.bottomView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:CGRectGetHeight(_bottomView.frame)?:49.0].active = YES;
    }
    else {
        self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
        NSDictionary *viewDic = @{@"collectionView":self.collectionView};
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[collectionView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[collectionView]|" options:0 metrics:nil views:viewDic]];
    }
    
}

- (UIView *)getDefaultBottomView {
    UIToolbar *bottomBar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    bottomBar.barStyle = UIBarStyleDefault;
    NSMutableArray *itemsArray = [NSMutableArray array];
    if (self.photoPickerStyle!=TFPhotoPickerStyleCollectionList) {
        UIBarButtonItem *cameraItem = [[UIBarButtonItem alloc] initWithImage:[TFPhotoResourceHelper imageNamed:@"photo_camera"] style:UIBarButtonItemStylePlain target:self action:@selector(p_bottomBarCameraItemAction)];
        [itemsArray addObject:cameraItem];
    }
    else {
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [itemsArray addObject:spaceItem];
    }
    if (_selectMaxCount) {
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [itemsArray addObject:spaceItem];
        UIBarButtonItem *selectCountItem = [[UIBarButtonItem alloc] init];
        [itemsArray addObject:selectCountItem];
        _selectCountItem = selectCountItem;
        [self p_updateBottomSelectCountItemTitle];
    }
    [bottomBar setItems:itemsArray];
    return bottomBar;
}

- (UIView *)getDefaultAuthorizationStatusDeniedView {
    return [[TFPhotoAuthDeniedView alloc] init];
}

- (UIView *)getDefaultNoPhotosView {
    UIView *photoView = [[UIView alloc] init];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = [TFPhotoResourceHelper localizedStringWithKey:@"无照片或视频"];
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = [UIFont systemFontOfSize:30];
    [photoView addSubview:titleLabel];
    
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.text = [TFPhotoResourceHelper localizedStringWithKey:@"您可以使用相机拍摄照片和视频或使用iTunes将照片和视频同步到iPhone。"];
    detailLabel.numberOfLines = 0;
    detailLabel.textColor = [UIColor lightGrayColor];
    detailLabel.font = [UIFont systemFontOfSize:18];
    detailLabel.textAlignment = NSTextAlignmentCenter;
    [photoView addSubview:detailLabel];
    UIButton *takePhotoButton = nil;
    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
        takePhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [takePhotoButton setTitle:[TFPhotoResourceHelper localizedStringWithKey:@"去拍摄"] forState:UIControlStateNormal];
        [takePhotoButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        takePhotoButton.titleLabel.font = [UIFont systemFontOfSize:20];
        takePhotoButton.layer.cornerRadius = 5.0;
        takePhotoButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
        takePhotoButton.layer.borderWidth = 1.0;
        [takePhotoButton addTarget:self action:@selector(p_bottomBarCameraItemAction) forControlEvents:UIControlEventTouchUpInside];
        [photoView addSubview:takePhotoButton];
        takePhotoButton.translatesAutoresizingMaskIntoConstraints = NO;
    }
    //添加约束
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    detailLabel.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *viewDic = @{@"detailLabel":detailLabel};
    
    [NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:photoView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:photoView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:detailLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:titleLabel attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0].active = YES;
    if (takePhotoButton) {
        [NSLayoutConstraint constraintWithItem:takePhotoButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:detailLabel attribute:NSLayoutAttributeBottom multiplier:1.0 constant:16.0].active = YES;
        [NSLayoutConstraint constraintWithItem:takePhotoButton attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:photoView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0].active = YES;
        [NSLayoutConstraint constraintWithItem:takePhotoButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:40.0].active = YES;
        [NSLayoutConstraint constraintWithItem:takePhotoButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:photoView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0].active = YES;
        [NSLayoutConstraint constraintWithItem:takePhotoButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:120.0].active = YES;

    }
    else {
        [NSLayoutConstraint constraintWithItem:detailLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:photoView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0].active = YES;
    }
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[detailLabel]-10-|" options:0 metrics:nil views:viewDic]];
    
    
    
    return photoView;
}

- (Class)photoPickerSectionHeaderViewClass {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerClassForMomentAlbumSectionHeaderView:)]) {
        return [self.delegate photoPickerViewControllerClassForMomentAlbumSectionHeaderView:self];
    }
    return [TFPhotoPickerCollectionViewSectionHeaderView class];
}

- (Class)photoPickerCellClass {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerCellClassForItem:)]) {
        return [self.delegate photoPickerViewControllerCellClassForItem:self];
    }
    return [TFPhotoPickerItemCollectionViewCell class];
}

- (Class)photoPickerTakePhotoCellClass {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerClassForTakePhotoCell:)]) {
        return [self.delegate photoPickerViewControllerClassForTakePhotoCell:self];
    }
    return [TFPhotoPickerTakePhotoCell class];
}

- (Class)photoBrowserDisplayCellClass {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerClassForPhotoBrowserDisplayCell:)]) {
        return [self.delegate photoPickerViewControllerClassForPhotoBrowserDisplayCell:self];
    }
    return [TFPhotoPickerPhotoBrowserDisplayCell class];
}

- (Class)photoBrowserVideoDisplayCellClass {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerClassForPhotoBrowserVideoDisplayCell:)]) {
        return [self.delegate photoPickerViewControllerClassForPhotoBrowserVideoDisplayCell:self];
    }
    return [TFPhotoPickerPhotoBrowserVideoDisplayCell class];
}

#pragma mark - private

- (void)p_checkAuthorizationStatus {
    //先获取当前状态
    [TFPhotoHandler checkAuthorizationStatusWithResult:^(BOOL isAuthed) {
        [self p_showViewWithAuthorised:isAuthed];
    }];
}

- (void)p_showViewWithAuthorised:(BOOL)authorised {
    if (authorised) {
        TFPhotoPickerLoadingView *loadingView = [TFPhotoPickerLoadingView showInView:self.view];
        dispatch_queue_t queue = dispatch_queue_create("CreateMomentModels", DISPATCH_QUEUE_CONCURRENT);
        //获取时刻数组
        dispatch_async(queue, ^{
            _allItemsArr = [NSMutableArray array];
            _momentFetchResult = [PHAssetCollection fetchMomentsWithOptions:nil];
            __block TFPhotoPickerItemModel *selectedItemModel = nil;
            self.momentArray = [TFPhotoPickerHelper getMomentsAlbumArrayWithMomentFetchResult:self.momentFetchResult mediaTypes:self.mediaTypes enumerateItemModels:^(TFPhotoPickerItemModel *itemModel) {
                [self.allItemsArr insertObject:itemModel atIndex:0];
                if ([self.selectAssetsArray containsObject:itemModel.asset]) {
                    itemModel.select = YES;
                    selectedItemModel = itemModel;
                    if (![self.selectPhotoIdentifiersArray containsObject:itemModel.asset.localIdentifier]) {
                        [self.selectPhotoIdentifiersArray addObject:itemModel.asset.localIdentifier];
                    }
                }
                else if ([self.selectPhotoIdentifiersArray containsObject:itemModel.asset.localIdentifier]) {
                    itemModel.select = YES;
                    selectedItemModel = itemModel;
                    if (![self.selectAssetsArray containsObject:itemModel.asset]) {
                        [self.selectAssetsArray addObject:itemModel.asset];
                    }
                }
            }];
            
            
            if (_selectMaxCount==1&&selectedItemModel) {
                NSInteger selectIndex = [self.allItemsArr indexOfObject:selectedItemModel];
                self.previousSelectedIndexPath = [NSIndexPath indexPathForRow:selectIndex+1 inSection:0];
            }

            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                    self.showType = TFPhotoPickerShowTypeAlbum;
                    
                    self.showModelsArr = [NSMutableArray arrayWithArray:self.allItemsArr];
                }
                else {
                    self.showModelsArr = [NSMutableArray arrayWithArray:self.momentArray];
                }
                self.bottomView.hidden = NO;
                [loadingView dismiss];
                if (self.showModelsArr.count) {
                    //滚动到最底部
                    [self p_collectionViewReloadAndScrollToPosition];
                }
                else {
                    //创建无照片和视频的view
                    [self p_addNoPhotosView];
                }
                
            });
        });
    }
    else {
        //创建授权失败view
        UIView *deniedView = [self getDefaultAuthorizationStatusDeniedView];
        deniedView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:deniedView];
            //添加约束
        [NSLayoutConstraint constraintWithItem:deniedView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0].active = YES;
        [NSLayoutConstraint constraintWithItem:deniedView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0.0].active = YES;
        [NSLayoutConstraint constraintWithItem:deniedView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:30.0].active = YES;
    }
}

- (void)p_addNoPhotosView {
    UIView *noPhotosView = [self getDefaultNoPhotosView];
    noPhotosView.translatesAutoresizingMaskIntoConstraints = NO;
    noPhotosView.tag = kTFPhotoPickerNoPhotosViewTag;
    [self.view addSubview:noPhotosView];
    
    [NSLayoutConstraint constraintWithItem:noPhotosView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:noPhotosView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:noPhotosView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0].active = YES;

    
}

- (void)p_removeNoPhotoView {
    UIView *noPhotoView = [self.view viewWithTag:kTFPhotoPickerNoPhotosViewTag];
    if (noPhotoView) {
        [noPhotoView removeFromSuperview];
    }
}

- (void)p_collectionViewReloadAndScrollToPosition {
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    [self.collectionView reloadData];
    switch (_showType) {
        case TFPhotoPickerShowTypeMoment:
        {
            flowLayout.headerReferenceSize = CGSizeMake(CGRectGetWidth(self.collectionView.frame), 44.0);
            TFPhotoPickerMomentModel *model = [self.showModelsArr lastObject];
            if (self.photoPickerStyle!=TFPhotoPickerStyleCollectionList) {
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:model.items.count-1 inSection:self.showModelsArr.count-1] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
            }
        }
            break;
        case TFPhotoPickerShowTypeAlbum: {
            flowLayout.headerReferenceSize = CGSizeMake(CGRectGetWidth(self.collectionView.frame), 0.0);
            if (self.photoPickerStyle!=TFPhotoPickerStyleCollectionList) {
                if (self.showModelsArr.count) {
                    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.showModelsArr.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
                }
            }
        }
            break;
        default:
            break;
    }
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    //获取当前屏幕方向，图片显示大小
    CGFloat itemWidth = [TFPhotoPickerHelper imageShowSize];
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    [self.collectionView layoutIfNeeded];
}

#pragma mark - view actions.

- (void)p_navigationItemCancelLeftItemAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)p_navigationItemAlbumListButtonAction:(UIButton *)sender {
    if (self.momentFetchResult.count) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            //创建临时已选择相册
            TFPhotoPickerAlbumModel *momentModel = nil;
            if (self.photoPickerStyle==TFPhotoPickerStyleMomentGroup) {
                if (self.momentArray.count) {
                    momentModel = [[TFPhotoPickerAlbumModel alloc] init];
                    momentModel.albumName = [TFPhotoResourceHelper localizedStringWithKey:@"时刻"];
                    momentModel.assetsCount = self.allItemsArr.count;
                    momentModel.assets = (PHFetchResult *)@[[[self.momentArray lastObject].items lastObject].asset];
                }
            }
            
            TFPhotoPickerAlbumModel *selectedModel = nil;
            if (_selectAssetsArray.count) {
                selectedModel = [[TFPhotoPickerAlbumModel alloc] init];
                selectedModel.albumName = [TFPhotoResourceHelper localizedStringWithKey:@"已选择"];
                selectedModel.assetsCount = self.selectAssetsArray.count;
                selectedModel.assets = (PHFetchResult *)[NSArray arrayWithArray:self.selectAssetsArray];
            }
            TFPhotoPickerAlbumView *albumView = [TFPhotoPickerAlbumView showInView:self.view withMomentAlbumModel:momentModel selectedAlbumModel:selectedModel mediaTypes:self.mediaTypes delegate:self];
            albumView.tag = kTFPhotoPickerAlbumViewTag;
        }
        else {
            TFPhotoPickerAlbumView *albumView = [self.view viewWithTag:kTFPhotoPickerAlbumViewTag];
            [albumView showAlbumListTableViewWithHidden:YES];
        }
    }
    
}

- (void)p_navigationItemConfirmRightItemAction {
    if (self.selectAssetsArray.count) {
        if ([self.delegate respondsToSelector:@selector(photoPickerViewController:didFinishPickWithSelectedAssetsArray:)]) {
            [self.delegate photoPickerViewController:self didFinishPickWithSelectedAssetsArray:self.selectAssetsArray];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"提示"] message:[NSString localizedStringWithFormat:[TFPhotoResourceHelper localizedStringWithKey:@"请至少选择一%@"],[self p_getTipMessageSuffix]] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"确定"] style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:confirmAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (NSString *)p_getTipMessageSuffix {
    NSString *suffix = @"";
    if (self.mediaTypes.count==1) {
        if ([[self.mediaTypes lastObject] integerValue]==PHAssetMediaTypeImage) {
            suffix = [TFPhotoResourceHelper localizedStringWithKey:@"张图片"];
        }
        else if ([[self.mediaTypes lastObject] integerValue]==PHAssetMediaTypeVideo) {
            suffix = [TFPhotoResourceHelper localizedStringWithKey:@"个视频"];
        }
        else if ([[self.mediaTypes lastObject] integerValue]==PHAssetMediaTypeAudio) {
            suffix = [TFPhotoResourceHelper localizedStringWithKey:@"个音频"];
        }
    }
    else if (self.mediaTypes.count>1) {
        suffix = [TFPhotoResourceHelper localizedStringWithKey:@"个媒体文件"];
    }
    return suffix;
}

- (BOOL)p_didReachMaxSelectCount {
    NSInteger selectCount = self.selectAssetsArray.count;
    selectCount += 1;
    return (selectCount>_selectMaxCount);
}

- (void)p_itemSelectCountIsOverMaxSelectCount {
    //越界处理
    if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerSelectCountIsOverMaxSelectCount:)]) {
        [self.delegate photoPickerViewControllerSelectCountIsOverMaxSelectCount:self];
    }
    else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString localizedStringWithFormat:[TFPhotoResourceHelper localizedStringWithKey:@"您最多只能选择%zd%@"],_selectMaxCount,[self p_getTipMessageSuffix]] message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"确定"] style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:alertAction];
        if (self.presentedViewController) {
            [self.presentedViewController presentViewController:alert animated:YES completion:nil];
        }
        else {
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}

- (void)p_updateCollectionHeaderViewWithSection:(NSInteger)section {
    UICollectionReusableView<TFPhotoPickerCollectionViewSectionHeaderViewPublic> *headerView = (UICollectionReusableView<TFPhotoPickerCollectionViewSectionHeaderViewPublic> *)[self.collectionView viewWithTag:kTFPhotoPickerSectionHeaderViewTag+section];
    [headerView reloadHeaderView];
}

- (void)p_updateBottomSelectCountItemTitle {
    _selectCountItem.title = [NSString localizedStringWithFormat:[TFPhotoResourceHelper localizedStringWithKey:@"已选%zd/%zd"],self.selectAssetsArray.count,self.selectMaxCount];
}

- (void)p_bottomBarCameraItemAction {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewControllerBottomBarCameraItemAction:)]) {
        [self.delegate photoPickerViewControllerBottomBarCameraItemAction:self];
    }
    else {
        NSMutableArray *mediaTypesArray = [NSMutableArray array];
        for (NSNumber *mediaType in self.mediaTypes) {
            if ([mediaType integerValue]==PHAssetMediaTypeImage) {
                [mediaTypesArray addObject:(NSString *)kUTTypeImage];
            }
            else if ([mediaType integerValue]==PHAssetMediaTypeVideo) {
                [mediaTypesArray addObject:(NSString *)kUTTypeMovie];
            }
            else if ([mediaType integerValue]==PHAssetMediaTypeAudio) {
                [mediaTypesArray addObject:(NSString *)kUTTypeAudio];
            }
        }
        
        [TFSinglePhotoPickerHelper showSystemSinglePhotoPickerInViewController:self withSourceType:UIImagePickerControllerSourceTypeCamera mediaTypes:mediaTypesArray allowsEditing:NO delegate:self];
    }
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    switch (_showType) {
        case TFPhotoPickerShowTypeMoment:
            return self.showModelsArr.count;
            break;
        case TFPhotoPickerShowTypeAlbum:
            return 1;
        default:
            break;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    switch (_showType) {
        case TFPhotoPickerShowTypeMoment:
        {
            TFPhotoPickerMomentModel *model = self.showModelsArr[section];
            return model.items.count;
        }
            break;
        case TFPhotoPickerShowTypeAlbum: {
            if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                return self.showModelsArr.count + 1;
            }
            else {
                return self.showModelsArr.count;
            }
        }
        default:
            break;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList&&indexPath.row==0) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([self photoPickerTakePhotoCellClass]) forIndexPath:indexPath];
        return cell;
    }
    else {
        UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([self photoPickerCellClass]) forIndexPath:indexPath];
        cell.model = [self p_getItemModelWithIndexPath:indexPath];
        cell.delegate = self;
        [cell reloadCell];
        return cell;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    switch (_showType) {
        case TFPhotoPickerShowTypeMoment:
        {
            UICollectionReusableView<TFPhotoPickerCollectionViewSectionHeaderViewPublic> *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([self photoPickerSectionHeaderViewClass]) forIndexPath:indexPath];
            headerView.tag = kTFPhotoPickerSectionHeaderViewTag + indexPath.section;
            headerView.model = self.showModelsArr[indexPath.section];
            headerView.delegate = self;
            [headerView reloadHeaderView];
            return headerView;
        }
            break;
        case TFPhotoPickerShowTypeAlbum: {
            return nil;
        }
            break;
        default:
            break;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList&&indexPath.row==0) {
        [self p_bottomBarCameraItemAction];
    }
    else {
        TFPhotoPickerItemModel *itemModel = [self p_getItemModelWithIndexPath:indexPath];
        switch (itemModel.modelType) {
            case TFPhotoPickerItemModelTypeNormal:
            {
                self.selectIndexPath = indexPath;
                TFPhotoBrowserViewController *photoBrowserVC = [[TFPhotoBrowserViewController alloc] init];
                photoBrowserVC.dataSource = self;
                photoBrowserVC.delegate = self;
                if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                    photoBrowserVC.currentPage = indexPath.row-1;
                }
                else {
                    photoBrowserVC.currentPage = indexPath.row;
                }
                UIBarButtonItem *selectCountItem =  [[UIBarButtonItem alloc] initWithTitle:[NSString localizedStringWithFormat:[TFPhotoResourceHelper localizedStringWithKey:@"已选%zd/%zd"],self.selectAssetsArray.count,self.selectMaxCount] style:UIBarButtonItemStylePlain target:nil action:nil];
                selectCountItem.tintColor = [UIColor whiteColor];
                [selectCountItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateDisabled];
                selectCountItem.enabled = NO;
                photoBrowserVC.topNavigationItem.rightBarButtonItem = selectCountItem;
                [self presentViewController:photoBrowserVC animated:YES completion:nil];
                
            }
                break;
            case TFPhotoPickerItemModelTypeDownloadImageFail: {
                UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *cell = (UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)[self.collectionView cellForItemAtIndexPath:indexPath];
                [cell startDownloadICloudImage];
            }
                break;
            default:
                break;
        }
    }
    
}

- (TFPhotoPickerItemModel *)p_getItemModelWithIndexPath:(NSIndexPath *)indexPath {
    switch (_showType) {
        case TFPhotoPickerShowTypeMoment:
        {
            TFPhotoPickerMomentModel *momentModel = self.showModelsArr[indexPath.section];
            return momentModel.items[indexPath.row];
        }
            break;
        case TFPhotoPickerShowTypeAlbum: {
            if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                return self.showModelsArr[indexPath.row-1];
            }
            else {
                return self.showModelsArr[indexPath.row];
            }
        }
        default:
            break;
    }
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (![cell isKindOfClass:[self photoPickerTakePhotoCellClass]]) {
        [[TFPhotoHandler sharedHandler] cacheThumbnailImageWithAssets:@[cell.model.asset] size:[TFPhotoPickerHelper imageSize]];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (![cell isKindOfClass:[self photoPickerTakePhotoCellClass]]) {
        [[TFPhotoHandler sharedHandler] clearCacheImagesWithAssets:@[cell.model.asset] size:[TFPhotoPickerHelper imageSize]];
    }
}

#pragma mark - TFPhotoPickerAlbumViewDelegate

- (void)photoPickerAlbumView:(TFPhotoPickerAlbumView *)photoPickerAlbumView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        TFPhotoPickerAlbumModel *albumModel = photoPickerAlbumView.albumListArray[indexPath.row];
        self.currentCollectionSubtype = albumModel.subType;
        if ([albumModel.albumName isEqualToString:[TFPhotoResourceHelper localizedStringWithKey:@"时刻"]]) {
            self.showType = TFPhotoPickerShowTypeMoment;
            self.showModelsArr = [NSMutableArray arrayWithArray:self.momentArray];
        }
        else {
            self.showType = TFPhotoPickerShowTypeAlbum;
            //筛选
            NSMutableArray *phAssetLocalIdentifierArray = [NSMutableArray array];
            for (PHAsset *asset in albumModel.assets) {
                [phAssetLocalIdentifierArray addObject:asset.localIdentifier];
            }
            //组建筛选谓词
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"asset.localIdentifier IN %@",phAssetLocalIdentifierArray];
            if (albumModel.subType==PHAssetCollectionSubtypeAlbumCloudShared|albumModel.subType==PHAssetCollectionSubtypeAlbumMyPhotoStream) {
                self.showModelsArr = [NSMutableArray arrayWithArray:photoPickerAlbumView.shareTypeItemModelArray];
            }
            else {
                self.showModelsArr = [NSMutableArray arrayWithArray:[self.allItemsArr filteredArrayUsingPredicate:predicate]];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.albumListButton setTitle:albumModel.albumName forState:UIControlStateNormal];
            [self.albumListButton setTitle:albumModel.albumName forState:UIControlStateSelected];
            [self.albumListButton sizeToFit];
            //刷新UI
            //滚动到最底部
            [self p_collectionViewReloadAndScrollToPosition];
        });
    });
}

- (void)photoPickerAlbumViewWillDissmiss:(TFPhotoPickerAlbumView *)photoPickerAlbumView {
    self.albumListButton.selected = NO;
}

#pragma mark - TFPhotoBrowserViewControllerDataSource

- (NSInteger)numberOfPhotosInPhotoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController {
    switch (_showType) {
        case TFPhotoPickerShowTypeMoment:
        {
            TFPhotoPickerMomentModel *model = self.showModelsArr[self.selectIndexPath.section];
            return model.fetchResult.count;
        }
            break;
        case TFPhotoPickerShowTypeAlbum: {
            return self.showModelsArr.count;
        }
            break;
        default:
            break;
    }
}

- (id)photoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController photoForIndex:(NSInteger)index {
    NSInteger row = index;
    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
        row += 1;
    }
    TFPhotoPickerItemModel *model = [self p_getItemModelWithIndexPath:[NSIndexPath indexPathForRow:row inSection:self.selectIndexPath.section]];
    return model.asset;
    
}

- (TFPhotoBrowserOriginalPhotoViewModel *)photoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController originalPhotoViewAtIndex:(NSInteger)index {
    NSInteger row = index;
    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
        row += 1;
    }
    TFPhotoPickerItemCollectionViewCell *cell = (TFPhotoPickerItemCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:self.selectIndexPath.section]];
    TFPhotoBrowserOriginalPhotoViewModel *model = [[TFPhotoBrowserOriginalPhotoViewModel alloc] init];
    model.originalImage = cell.photoImageView.image;
    model.originalPhotoView = cell.photoImageView;
    return model;
}

- (Class)photoBrowserViewControllerCellClassForDisplay:(TFPhotoBrowserViewController *)photoBrowserViewController {
    return [self photoBrowserDisplayCellClass];
}

- (Class)photoBrowserViewControllerVideoCellClassForDisplay:(TFPhotoBrowserViewController *)photoBrowserViewController {
    return [self photoBrowserVideoDisplayCellClass];
}

#pragma mark - TFPhotoBrowserViewControllerDelegate

- (void)photoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController didReloadCell:(TFPhotoPickerPhotoBrowserDisplayCell *)cell {
    __weak typeof(self) weakSelf = self;
    __weak typeof(cell) weakCell = cell;
    __weak typeof(photoBrowserViewController) weakPhotoVC = photoBrowserViewController;
    cell.selectButtonActionBlock = ^(UIButton *sender) {
        BOOL select = !sender.selected;
        NSInteger row = weakCell.indexPath.row;
        if (weakSelf.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
            row +=1;
        }
        if ([weakSelf p_selectItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:weakSelf.selectIndexPath.section]]) {
            sender.selected = select;
            weakPhotoVC.topNavigationItem.rightBarButtonItem.title = [NSString localizedStringWithFormat:[TFPhotoResourceHelper localizedStringWithKey:@"已选%zd/%zd"],weakSelf.selectAssetsArray.count,weakSelf.selectMaxCount];
        }
    };
    NSInteger row = cell.indexPath.row;
    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
        row += 1;
    }
    BOOL select = [self p_getItemModelWithIndexPath:[NSIndexPath indexPathForRow:row inSection:self.selectIndexPath.section]].select;
    [cell setSelectButtonTransformWithNavigationBarHidden:photoBrowserViewController.topNavigationBarHidden animated:NO];
    [cell setSelectButtonSelect:select];
}

- (void)photoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController cellDidLoadPhoto:(TFPhotoPickerPhotoBrowserDisplayCell *)cell {
    [cell setSelectButtonHidden:YES];
}

- (void)photoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController cellDidFinishLoadPhoto:(TFPhotoPickerPhotoBrowserDisplayCell *)cell {
    [cell setSelectButtonHidden:NO];
}

- (void)photoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController cellDidFinishLoadPhotoFromICloud:(TFPhotoPickerPhotoBrowserDisplayCell *)cell {
    [cell setSelectButtonHidden:NO];
}

- (void)photoBrowserViewController:(TFPhotoBrowserViewController *)photoBrowserViewController navigationBarAndBottomBarDoMoveAnimationWithHidden:(BOOL)hidden {
    TFPhotoPickerPhotoBrowserDisplayCell *cell = (TFPhotoPickerPhotoBrowserDisplayCell *)[photoBrowserViewController currentDisplayCell];
    [cell setSelectButtonTransformWithNavigationBarHidden:photoBrowserViewController.topNavigationBarHidden animated:NO];
}

#pragma mark - TFPhotoPickerItemCollectionViewCellDelegate

- (void)photoPickerItemCollectionViewCell:(__kindof UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)cell didClickSelectButton:(UIButton *)sender {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [self p_selectItemAtIndexPath:indexPath];
}

- (void)photoPickerItemCollectionViewCellDidFinishDownloadImageFromICloud:(__kindof UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)cell {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [self p_selectItemAtIndexPath:indexPath];
}

- (BOOL)p_selectItemAtIndexPath:(NSIndexPath *)indexPath {
    TFPhotoPickerItemModel *model = [self p_getItemModelWithIndexPath:indexPath];
    if (_selectMaxCount==1) {
        BOOL shouldSelect = !model.select;
        //先检测图片是否需要从iCloud上下载
        UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *cell = (UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)[self.collectionView cellForItemAtIndexPath:indexPath];
        BOOL shouldDownload = [model shouldDownloadFromICloud];
        if (shouldDownload) {
            //开始从iCloud下载图片
            [cell startDownloadICloudImage];
        }
        else {
            //取消上次选择
            if (_previousSelectedIndexPath) {
                [self p_doSelectItemWithSelect:NO indexPath:_previousSelectedIndexPath];
            }
            [self p_doSelectItemWithSelect:YES indexPath:indexPath];
        }
        return shouldSelect;
    }
    else {
        BOOL select = model.select;
        if (select) {
            //取消选中
            [self p_doSelectItemWithSelect:NO indexPath:indexPath];
            return YES;
        }
        else {
            //先检测当前是否越界
            BOOL isReachMax = [self p_didReachMaxSelectCount];
            if (!isReachMax) {
                //先检测图片是否需要从iCloud上下载
                UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *cell = (UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)[self.collectionView cellForItemAtIndexPath:indexPath];
                BOOL shouldDownload = [model shouldDownloadFromICloud];
                if (shouldDownload) {
                    //开始从iCloud下载图片
                    [cell startDownloadICloudImage];
                }
                else {
                    [self p_doSelectItemWithSelect:YES indexPath:indexPath];
                }
            }
            else {
                [self p_itemSelectCountIsOverMaxSelectCount];
            }
            return !isReachMax;
        }
    }
    
}

- (void)p_doSelectItemWithSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath{
    TFPhotoPickerItemModel *model = [self p_getItemModelWithIndexPath:indexPath];
    model.select = select;
    if (select) {
        model.momentModel.selectCount += 1;
        [self.selectAssetsArray addObject:model.asset];
        [self.selectPhotoIdentifiersArray addObject:model.asset.localIdentifier];
        _previousSelectedIndexPath = indexPath;
        if ([self.delegate respondsToSelector:@selector(photoPickerViewController:didSelectAsset:)]) {
            [self.delegate photoPickerViewController:self didSelectAsset:model.asset];
        }
    }
    else {
        model.momentModel.selectCount -=1;
        [self.selectAssetsArray removeObject:model.asset];
        [self.selectPhotoIdentifiersArray removeObject:model.asset.localIdentifier];
        if ([self.delegate respondsToSelector:@selector(photoPickerViewController:didDeselectAsset:)]) {
            [self.delegate photoPickerViewController:self didDeselectAsset:model.asset];
        }
    }
    //更新UI
    switch (_showType) {
        case TFPhotoPickerShowTypeMoment:
        {
            [self p_updateCollectionHeaderViewWithSection:indexPath.section];
        }
            break;
        case TFPhotoPickerShowTypeAlbum: {
            
        }
            break;
        default:
            break;
    }
    //执行动画
    [self p_updateBottomSelectCountItemTitle];
    UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *cell = (UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)[self.collectionView cellForItemAtIndexPath:indexPath];
    if (!cell) {
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    }
    else {
        [cell doSelectWithAnimated:YES];
    }
}

- (void)photoPickerItemCollectionViewCellDidReloadCell:(__kindof UICollectionViewCell<TFPhotoPickerItemCollectionViewCellPublic> *)cell {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewController:didReloadCell:atIndexPath:)]) {
        [self.delegate photoPickerViewController:self didReloadCell:cell atIndexPath:[self.collectionView indexPathForCell:cell]];
    }
}

#pragma mark - TFPhotoPickerCollectionViewSectionHeaderViewDelegate

- (void)photoPickerCollectionViewSectionHeaderView:(__kindof UICollectionReusableView<TFPhotoPickerCollectionViewSectionHeaderViewPublic> *)headerView didClickSelectAllButton:(UIButton *)sender {
    TFPhotoPickerMomentModel *momentModel = headerView.model;
    NSInteger section = [_momentArray indexOfObject:momentModel];
    //判断是否越界
    BOOL select = !sender.selected;
    if (select) {
        NSInteger selectCount = self.selectAssetsArray.count + momentModel.items.count - momentModel.selectCount;
        if (selectCount>_selectMaxCount) {
            [self p_itemSelectCountIsOverMaxSelectCount];
            return;
        }
    }
    for (NSInteger row = 0; row<momentModel.items.count; row++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
        TFPhotoPickerItemModel *model = momentModel.items[row];
        if (model.select!=select) {
            [self p_selectItemAtIndexPath:indexPath];
        }
    }
}

- (void)photoPickerCollectionViewSectionHeaderViewDidReloadView:(__kindof UICollectionReusableView<TFPhotoPickerCollectionViewSectionHeaderViewPublic> *)headerView {
    if ([self.delegate respondsToSelector:@selector(photoPickerViewController:didReloadHeaderView:)]) {
        [self.delegate photoPickerViewController:self didReloadHeaderView:headerView];
    }
}

#pragma mark - TFSinglePhotoPickerHelperDelegate

- (void)singlePhotoPickerHelper:(TFSinglePhotoPickerHelper *)photoPickerHelper picker:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [self dismissViewControllerAnimated:YES completion:nil];
    //先开始定位
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *request = nil;
        if (info[UIImagePickerControllerMediaType]==(NSString *)kUTTypeMovie) {
            request = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:info[UIImagePickerControllerMediaURL]];
        }
        else if (info[UIImagePickerControllerMediaType]==(NSString *)kUTTypeImage) {
            UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
            //保存图片
            request = [PHAssetChangeRequest creationRequestForAssetFromImage:originalImage];
        }
        if (self.selectAssetsArray.count<self.selectMaxCount) {
            _autoSelectAssetIdentifier = request.placeholderForCreatedAsset.localIdentifier;
        }
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            NSLog(@"保存图片成功");
        }
        else {
            NSLog(@"保存图片失败");
        }
    }];
}

#pragma mark - PHPhotoLibraryChangeObserver

- (void)photoLibraryDidChange:(PHChange *)changeInstance {
    PHFetchResultChangeDetails *momentChangeDetail = [changeInstance changeDetailsForFetchResult:_momentFetchResult];
    if (momentChangeDetail.hasIncrementalChanges) {
        if (momentChangeDetail.removedObjects.count) {
            //移除缓存图片
            for (PHAssetCollection *collection in momentChangeDetail.removedObjects) {
                TFPhotoPickerMomentModel *model = [[_momentArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"localIdentifier = %@",collection.localIdentifier]] lastObject];
                NSMutableArray *assetsArray = [NSMutableArray array];
                NSMutableArray *assetsIdsArray = [NSMutableArray array];
                for (PHAsset *asset in model.fetchResult) {
                    [assetsArray addObject:asset];
                    [assetsIdsArray addObject:asset.localIdentifier];
                }
                //移除数据源
                [self.selectAssetsArray removeObjectsInArray:assetsArray];
                [self.selectPhotoIdentifiersArray removeObjectsInArray:assetsIdsArray];
                [[TFPhotoHandler sharedHandler] clearCacheImagesWithAssets:assetsArray size:[TFPhotoPickerHelper imageSize]];
                //移除数据源
                [self.allItemsArr removeObjectsInArray:model.items];
                [self.momentArray removeObject:model];
                if (self.showType == TFPhotoPickerShowTypeAlbum) {
                    if ((self.currentCollectionSubtype == collection.assetCollectionSubtype)||(self.photoPickerStyle == TFPhotoPickerStyleCollectionList)) {
                        [self.showModelsArr removeObjectsInArray:model.items];
                    }
                }
            }
        }
        if (momentChangeDetail.insertedObjects.count) {
            NSMutableArray *assetsArray = [NSMutableArray array];
            for (PHAssetCollection *collection in momentChangeDetail.insertedObjects) {
                TFPhotoPickerMomentModel *momentModel = [TFPhotoPickerHelper createMomentModelWithPHAssetCollection:collection mediaTypes:self.mediaTypes enumerateItemModels:^(TFPhotoPickerItemModel *itemModel) {
                    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                        [self.allItemsArr insertObject:itemModel atIndex:0];
                    }
                    else {
                        [self.allItemsArr addObject:itemModel];
                    }
                    if ([itemModel.asset.localIdentifier isEqualToString:_autoSelectAssetIdentifier]) {
                        itemModel.select = YES;
                        [self.selectAssetsArray addObject:itemModel.asset];
                        [self.selectPhotoIdentifiersArray addObject:itemModel.asset.localIdentifier];
                        _autoSelectAssetIdentifier = nil;
                        if (self.showType==TFPhotoPickerShowTypeAlbum) {
                            if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                                _previousSelectedIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
                            }
                            else {
                                _previousSelectedIndexPath = [NSIndexPath indexPathForRow:_showModelsArr.count inSection:0];
                            }
                        }
                        else {
                            _previousSelectedIndexPath = [NSIndexPath indexPathForRow:assetsArray.count inSection:self.momentArray.count];
                        }
                    }
                    [assetsArray addObject:itemModel.asset];
                }];
                if (momentModel) {
                    [self.momentArray addObject:momentModel];
                }
                if (self.showType == TFPhotoPickerShowTypeAlbum) {
                    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                        [self.showModelsArr insertObjects:momentModel.items atIndexes:[NSIndexSet indexSetWithIndex:0]];
                    }
                    else {
                        if (self.currentCollectionSubtype == collection.assetCollectionSubtype) {
                            [self.showModelsArr addObjectsFromArray:momentModel.items];
                        }
                    }
                }
                
                
            }
        }
        
        if (momentChangeDetail.changedObjects.count) {
            
            for (PHAssetCollection *collection in momentChangeDetail.changedObjects) {
                
                TFPhotoPickerMomentModel *changedMomentModel = [[_momentArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"localIdentifier = %@",collection.localIdentifier]] lastObject];
                if (changedMomentModel) {
                    PHFetchResultChangeDetails *itemChangeDetail = [changeInstance changeDetailsForFetchResult:changedMomentModel.fetchResult];
                    if (itemChangeDetail.removedObjects.count) {
                        //移除缓存图片
                        NSMutableArray *removeAssetArray = [NSMutableArray array];
                        NSMutableArray *removeItemsIdsArray = [NSMutableArray array];
                        
                        for (PHAsset *asset in itemChangeDetail.removedObjects) {
                            [removeAssetArray addObject:asset];
                            [removeItemsIdsArray addObject:asset.localIdentifier];
                        }
                        NSArray *removeItemsArray = [changedMomentModel.items filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"asset.localIdentifier = %@",removeItemsIdsArray]];
                        //移除数据源
                        [self.selectAssetsArray removeObjectsInArray:removeAssetArray];
                        [self.selectPhotoIdentifiersArray removeObjectsInArray:removeItemsIdsArray];
                        [self.allItemsArr removeObjectsInArray:removeItemsArray];
                        [changedMomentModel.items removeObjectsInArray:removeItemsArray];
                        if (self.showType == TFPhotoPickerShowTypeAlbum) {
                            if ((self.currentCollectionSubtype == collection.assetCollectionSubtype)||(self.photoPickerStyle == TFPhotoPickerStyleCollectionList)) {
                                [self.showModelsArr removeObjectsInArray:removeItemsArray];
                            }
                        }
                        //清空缓存图片
                        [[TFPhotoHandler sharedHandler] clearCacheImagesWithAssets:itemChangeDetail.removedObjects size:[TFPhotoPickerHelper imageSize]];
                    }
                    
                    if (itemChangeDetail.insertedObjects.count) {
                        //添加数据源
                        NSMutableArray *insetItemArray = [NSMutableArray array];
                        for (PHAsset *asset in itemChangeDetail.insertedObjects) {
                            TFPhotoPickerItemModel *itemModel = [TFPhotoPickerHelper createItemModelWithAsset:asset momentModel:changedMomentModel];
                            if ([itemModel.asset.localIdentifier isEqualToString:_autoSelectAssetIdentifier]) {
                                itemModel.select = YES;
                                [self.selectPhotoIdentifiersArray addObject:itemModel.asset.localIdentifier];
                                [self.selectAssetsArray addObject:asset];
                                _autoSelectAssetIdentifier = nil;
                                if (self.showType==TFPhotoPickerShowTypeAlbum) {
                                    if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                                        _previousSelectedIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
                                    }
                                    else {
                                        _previousSelectedIndexPath = [NSIndexPath indexPathForRow:_showModelsArr.count inSection:0];
                                    }
                                }
                                else {
                                    _previousSelectedIndexPath = [NSIndexPath indexPathForRow:changedMomentModel.items.count+insetItemArray.count inSection:[self.momentArray indexOfObject:changedMomentModel]];
                                }
                            }
                            //更新位置信息
                            [insetItemArray addObject:itemModel];
                        }
                        //改变数据源
                        if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                            [self.allItemsArr insertObjects:insetItemArray atIndexes:[NSIndexSet indexSetWithIndex:0]];
                        }
                        else {
                            [self.allItemsArr addObjectsFromArray:insetItemArray];
                        }
                        [changedMomentModel.items addObjectsFromArray:insetItemArray];
                        if (self.showType == TFPhotoPickerShowTypeAlbum) {
                            if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                                [self.showModelsArr insertObjects:insetItemArray atIndexes:[NSIndexSet indexSetWithIndex:0]];
                            }
                            else {
                                if (self.currentCollectionSubtype == collection.assetCollectionSubtype) {
                                    [self.showModelsArr addObjectsFromArray:insetItemArray];
                                }
                            }
                        }
                    }
                    
                    if (itemChangeDetail.changedObjects.count) {
                        for (PHAsset *asset in itemChangeDetail.changedObjects) {
                            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"asset.localIdentifier = %@",collection.localIdentifier];
                            TFPhotoPickerItemModel *itemModel = [[changedMomentModel.items filteredArrayUsingPredicate:predicate] lastObject];
                            itemModel.asset = asset;
                            itemModel.image = nil;
                        }
                    }
                    //赋值新的值
                    changedMomentModel.fetchResult = itemChangeDetail.fetchResultAfterChanges;
                }
                else {
                    NSMutableArray *assetsArray = [NSMutableArray array];
                    TFPhotoPickerMomentModel *momentModel = [TFPhotoPickerHelper createMomentModelWithPHAssetCollection:collection mediaTypes:self.mediaTypes enumerateItemModels:^(TFPhotoPickerItemModel *itemModel) {
                        if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                            [self.allItemsArr insertObject:itemModel atIndex:0];
                        }
                        else {
                            [self.allItemsArr addObject:itemModel];
                        }
                        if ([itemModel.asset.localIdentifier isEqualToString:_autoSelectAssetIdentifier]) {
                            itemModel.select = YES;
                            [self.selectAssetsArray addObject:itemModel.asset];
                            [self.selectPhotoIdentifiersArray addObject:itemModel.asset.localIdentifier];
                            if (self.showType==TFPhotoPickerShowTypeAlbum) {
                                if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                                    _previousSelectedIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
                                }
                                else {
                                    _previousSelectedIndexPath = [NSIndexPath indexPathForRow:_showModelsArr.count inSection:0];
                                }
                            }
                            else {
                                _previousSelectedIndexPath = [NSIndexPath indexPathForRow:assetsArray.count inSection:self.momentArray.count];
                            }
                            _autoSelectAssetIdentifier = nil;
                        }
                        [assetsArray addObject:itemModel.asset];
                    }];
                    if (momentModel) {
                        [self.momentArray addObject:momentModel];
                        
                        if (self.showType == TFPhotoPickerShowTypeAlbum) {
                            if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
                                [self.showModelsArr insertObjects:momentModel.items atIndexes:[NSIndexSet indexSetWithIndex:0]];
                            }
                            else {
                                if (self.currentCollectionSubtype == collection.assetCollectionSubtype) {
                                    [self.showModelsArr addObjectsFromArray:momentModel.items];
                                }
                            }
                        }
                    }
                    
                }
                
            }
        }
        _momentFetchResult = momentChangeDetail.fetchResultAfterChanges;
        dispatch_async(dispatch_get_main_queue(), ^{
            //重新筛选数据源
            if ((_momentFetchResult.count)||(self.photoPickerStyle==TFPhotoPickerStyleCollectionList)) {
                [self p_removeNoPhotoView];
                //滚动到最底部
                [self p_collectionViewReloadAndScrollToPosition];
            }
            else {
                [self p_addNoPhotosView];
            }
            [self p_updateBottomSelectCountItemTitle];
        });
    }
}

#pragma mark - lazy load.

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *flowLayout = nil;
        float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (systemVersion<9.0) {
            flowLayout = [[TFPhotoPickerCollectionViewFlowLayout alloc] init];
        }
        else {
            flowLayout = [[UICollectionViewFlowLayout alloc] init];
            flowLayout.sectionHeadersPinToVisibleBounds = YES;
        }
        CGFloat minSpace = [TFPhotoPickerHelper imageMinSpace];
        flowLayout.headerReferenceSize = CGSizeMake(CGRectGetWidth(self.view.frame), 44.0);
        flowLayout.minimumLineSpacing = minSpace;
        flowLayout.minimumInteritemSpacing = minSpace;
        CGFloat itemWidth = [TFPhotoPickerHelper imageShowSize];
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        Class cellClass = [self photoPickerCellClass];
        Class headerViewClass = [self photoPickerSectionHeaderViewClass];
        [_collectionView registerClass:cellClass forCellWithReuseIdentifier:NSStringFromClass(cellClass)];
        [_collectionView registerClass:headerViewClass forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass(headerViewClass)];
        if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
            [_collectionView registerClass:[self photoPickerTakePhotoCellClass] forCellWithReuseIdentifier:NSStringFromClass([self photoPickerTakePhotoCellClass])];
        }
    }
    return _collectionView;
}

- (UIButton *)albumListButton {
    if (!_albumListButton) {
        _albumListButton = [TFPhotoPickerAlbumButton buttonWithType:UIButtonTypeCustom];
        _albumListButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5.0, 0.0, 0.0);
        if (self.photoPickerStyle==TFPhotoPickerStyleCollectionList) {
            [_albumListButton setTitle:[TFPhotoResourceHelper localizedStringWithKey:@"所有照片"] forState:UIControlStateNormal];
        }
        else {
            [_albumListButton setTitle:[TFPhotoResourceHelper localizedStringWithKey:@"时刻"] forState:UIControlStateNormal];
        }
        UIColor *titleColor = [[UINavigationBar appearance] titleTextAttributes][NSForegroundColorAttributeName];
        if (!titleColor) {
            if (self.navigationController.navigationBar.barTintColor) {
                titleColor = self.navigationController.navigationBar.barTintColor;
            }
            else {
                titleColor = [UIColor blackColor];
            }
        }
        _albumListButton.tintColor = titleColor;
        [_albumListButton setTitleColor:titleColor forState:UIControlStateNormal];
        [_albumListButton setTitleColor:titleColor forState:UIControlStateSelected];
        
        UIImage *normalImage = [[TFPhotoResourceHelper imageNamed:@"photo_arrow_down"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [_albumListButton setImage:normalImage forState:UIControlStateNormal];
        
        UIImage *selectImage = [[TFPhotoResourceHelper imageNamed:@"photo_arrow_up"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [_albumListButton setImage:selectImage forState:UIControlStateSelected];
        
        [_albumListButton addTarget:self action:@selector(p_navigationItemAlbumListButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_albumListButton sizeToFit];
    }
    return _albumListButton;
}

- (NSArray<NSNumber *> *)mediaTypes {
    if (!_mediaTypes) {
        _mediaTypes = @[@(PHAssetMediaTypeImage)];
    }
    return _mediaTypes;
}

- (NSMutableArray<PHAsset *> *)selectAssetsArray {
    if (!_selectAssetsArray) {
        _selectAssetsArray = [NSMutableArray array];
    }
    return _selectAssetsArray;
}

- (NSMutableArray<NSString *> *)selectPhotoIdentifiersArray {
    if (!_selectPhotoIdentifiersArray) {
        _selectPhotoIdentifiersArray = [NSMutableArray array];
    }
    return _selectPhotoIdentifiersArray;
}

- (void)dealloc {
    //清空缓存图片
    [[TFPhotoHandler sharedHandler] clearAllCacheImages];
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
    NSLog(@"\n******************************************\n %s---line:%d \n******************************************",__func__,__LINE__);

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
